package com.mi9688.optional;

import java.util.Optional;
import java.util.Random;

public class Test03 {
    public static void main(String[] args) {
        User user = null;
        // 模拟不确定的空对象
        Random random = new Random();
        if (random.nextInt(11) > 5) {
            user = new User("Bob");
        }

        // 使用Optional类来包装空对象
        //Lambda表达式链式处理写法
        Optional<String> optionalS1 = Optional.ofNullable(user).map(u->u.getName()).map(name->name.toLowerCase());
        // 输出结果,若空则设置默认值为MiJiu
        System.out.println(optionalS1.orElse("MiJiu"));
        //非空则输出结果
        optionalS1.ifPresent(s->System.out.println(s));

        System.out.println("--------------------------------");

        //用方法引用简化
        Optional<String> optionalS2 = Optional.ofNullable(user).map(User::getName).map(String::toLowerCase);
        System.out.println(optionalS2.orElse("MiJiu"));
        optionalS1.ifPresent(System.out::println);


    }
}
